// pages/postDetail/postDetail.js
const postsData = require('../../data/posts-data.js')

const app = getApp()

Page({
  /**
   * 页面的初始数据
   */
  data: {},

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(option) {
    console.log(option)
    const postId = option.id
    this.data.currentPostId = postId
    const postData = postsData.postList[postId]
    this.setData({
      item: postData
    })

    let postsCollected = wx.getStorageSync('posts_collected')
    if (!postsCollected) {
      postsCollected = {}
      postsCollected[postId] = false
      wx.setStorageSync('posts_collected', postsCollected)
    } else {
      const postCollected = postsCollected[postId]
      this.setData({
        isCollected: postCollected
      })
    }

    if (
      app.globalData.isPlayingMusic &&
      app.globalData.currentMusicPostId === postId
    ) {
      this.setData({
        isPlayingMusic: true
      })
    }
  },
  handleCollect() {
    const postsCollected = wx.getStorageSync('posts_collected')
    postsCollected[this.data.currentPostId] = !postsCollected[
      this.data.currentPostId
    ]
    wx.setStorageSync('posts_collected', postsCollected)
    this.showToast(postsCollected[this.data.currentPostId])
  },
  showToast(isCollected) {
    this.setData({
      isCollected
    })
    wx.showToast({
      title: isCollected ? '收藏成功' : '取消成功',
      duration: 1000,
      icon: 'success'
    })
  },
  handleMusicTap() {
    const { currentPostId, isPlayingMusic } = this.data
    const postData = postsData.postList[currentPostId]
    const backgroundAudioManager = wx.getBackgroundAudioManager()

    if (!isPlayingMusic) {
      backgroundAudioManager.title = postData.music.title
      backgroundAudioManager.coverImgUrl = postData.music.coverImg
      // 设置了 src 之后会自动播放
      backgroundAudioManager.src = postData.music.url
      backgroundAudioManager.play()

      this.setData({
        isPlayingMusic: true
      })
      app.globalData.isPlayingMusic = true
      app.globalData.currentMusicPostId = currentPostId
    } else {
      backgroundAudioManager.pause()
      this.setData({
        isPlayingMusic: false
      })
      app.globalData.isPlayingMusic = false
    }
  }
})
